import { ReactElement, Key, useRef, useEffect, useState } from 'react'
import { Modal, Form, FormInstance, Select, message, Input } from 'antd'
import { caseInputRequest, getSeriesRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import Text from '@components/text'
import Dictionary, { DictionaryItem } from '@js/dictionary'
import { Dispatch } from 'redux'
import { useDispatch } from 'react-redux'
import { addWindow, delWindow } from '@src/redux/actions/tab'
import { SeriesSchema } from '@components/schema/seriesCase';

const { Item } = Form
const { TextArea } = Input
const { Option } = Select

async function getSeriesData (id: string, dispatch: Dispatch){
  const h = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getSeriesRequest(id))
  h()
  if (e === null && d !== null) {
    dispatch(addWindow({
      id: `series-case-list-${id}`,
      title: d.serieno,
      componentName: 'SeriesCaseList',
      forceRefresh: true,
      meta: {id}
    }))
  }
}

async function submitHandle (data: { [k: string]: any }, keys: React.Key[], seriesData: SeriesSchema, dispatch: Dispatch, hide: () => void): Promise<void> {
  delete data.num
  data.caseids = keys.join()
  const h = message.loading('提交中', 120)
  data.type = data.type.join()
  const [e, d] = await awaitWrap(caseInputRequest(data))
  h()
  if (e === null && d !== null) {
    hide()
    const id = d instanceof Array ? d[0] : d
    if (seriesData) {
      dispatch(delWindow(`series-case-input-${seriesData.id}`))
      dispatch(addWindow({
        id: `series-case-list-${id}`,
        title: seriesData.serieno,
        componentName: 'SeriesCaseList',
        forceRefresh: true,
        meta: {id}
      }))
    } else {
      dispatch(delWindow('series-case-input'))
      getSeriesData(id as string, dispatch)
    }
    message.success('导入成功').then(null, null)
  }
}

interface Props {
  visible: boolean
  hide: () => void
  keys: Key[]
  seriesData: SeriesSchema
}

function Main ({ visible, hide, keys, seriesData }: Props): ReactElement {
  const dispatch = useDispatch()
  const formRef = useRef<FormInstance>(null)
  const [options, setOptions] = useState<DictionaryItem[]>([])
  const [typeOptions, setTypeOptions] = useState<DictionaryItem[]>([])
  useEffect(() => {
    const c = formRef.current
    if (c !== null) {
      c.setFieldsValue({ num: keys.length })
    }
  }, [keys, formRef])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      c.resetFields()
    }
  }, [visible, formRef])
  useEffect(() => {
    const d = new Dictionary()
    d.init('系列案标签,系列案类型')
      .then(() => {
        setOptions(d.getList('系列案标签'))
        setTypeOptions(d.getList('系列案类型'))
      })
      .catch(e => console.error(e))
  }, [])
  return (
    <Modal title='创建系列案' visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()} maskClosable={false} destroyOnClose>
      <Form ref={formRef} labelCol={{ flex: '98px' }} initialValues={{ num: keys.length }} onFinish={async d => await submitHandle(d, keys, seriesData, dispatch, hide)}>
        <Item name='num' label='案件数'>
          <Text />
        </Item>
        <Item name='type' label='系列案类型' rules={[{ required: true, message: '系列案类型不能为空' }]}>
          <Select placeholder='请选择' mode='multiple'>
            {typeOptions.map((li, i) => <Option key={i} value={li.value}>{li.title}</Option>)}
          </Select>
        </Item>
        <Item name='tag' label='标签' rules={[{ required: true, message: '标签不能为空' }]}>
          <Select placeholder='请选择'>
            {options.map((li, i) => <Option key={i} value={li.value}>{li.title}</Option>)}
          </Select>
        </Item>
        <Item name='remark' label='备注'>
          <TextArea autoSize={{ minRows: 3 }} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
